package cn.maxmc.murderaddons.machine

import cn.maxmc.murderaddons.task.TaskType
import org.bukkit.Location
import org.bukkit.configuration.serialization.ConfigurationSerializable
import org.bukkit.configuration.serialization.SerializableAs
import org.bukkit.entity.Player
import java.util.*
import kotlin.collections.ArrayList

abstract class BaseMachine(private val type: MachineType,val taskType: TaskType,val mainLocation: Location,vararg locations: Location): ConfigurationSerializable {
    val locations = ArrayList(locations.toList())
    private val taskMap = HashMap<Player,Boolean>()

    val cache = ArrayList<Player>()

    @Suppress("UNCHECKED_CAST")
    constructor(map: Map<String,Any>): this(
        MachineType.valueOf(map["type"] as String),
        TaskType.valueOf(map["task_type"] as String),
        map["loc"] as Location,
        *(map["locs"] as List<Location>).toTypedArray()
    )

    abstract fun requestTask(player: Player,loc: Location)

    fun addTask(player: Player) {
        taskMap[player] = false
    }

    fun finish(player: Player) {
        cache.remove(player)
        taskMap[player] = true
    }

    fun isFinish(player: Player): Boolean {
        if( !taskMap.contains(player) ) {
            throw IllegalArgumentException("The given player don't have this task.")
        }
        return taskMap[player]!!
    }

    fun reset() {
        taskMap.clear()
    }

    override fun serialize(): MutableMap<String, Any> {
        return mutableMapOf(
            "type" to type.name,
            "task_type" to taskType.name,
            "loc" to mainLocation,
            "locs" to locations
        )
    }

}